package com.xltt.watchclient;

import android.util.Log;

import java.text.MessageFormat;

/**
 * Created by liwang on 2018/4/14.
 */

public class LogTool {
    public static final String TAG = "LogTool";
    public static final boolean debug = true;
    public static final String logFormat = "class:{0},method:{1},line:{2},msg:{3}";

    public static StackTraceElement getCallerStack() {
        StackTraceElement[] stacks = Thread.currentThread().getStackTrace();
        if (stacks.length > 5) {
            return stacks[5];
        }
        return null;
    }

    public static String getTag(StackTraceElement callerStackEle) {
        if (callerStackEle == null)
            return "";
        String className = callerStackEle.getClassName();
        String simpleClassName = className.substring(className.lastIndexOf('.') + 1);
        return simpleClassName;
    }

    public static void d(String msg) {
        if (debug) {
            String buildMsg = buildLogMsg(msg);
            Log.d(TAG, buildMsg);
        }
    }

    public static void i(String msg) {
        String buildMsg = buildLogMsg(msg);
        Log.i(TAG, buildMsg);
    }

    public static void d(String msg, boolean file) {
        if (debug) {
            String buildMsg = buildLogMsg(msg);
            Log.d(TAG, buildMsg);
        }
    }


    public static void e(String ms) {
        if (debug) {
            StackTraceElement stack = getCallerStack();
            String buildMsg = buildLogMsg(ms);
            Log.e(getTag(stack), buildMsg);
        }
    }

    public static void e(Throwable t) {
        if (debug) {
            StackTraceElement stack = getCallerStack();
            String buildMsg = buildLogMsg(t.getMessage());
            Log.e(getTag(stack), buildMsg, t);
        }
    }

    public static void e(String msg, Throwable t) {
        if (debug) {
            String buildMsg = buildLogMsg(msg);
            Log.e(TAG, buildMsg, t);
        }
    }

    public static String buildLogMsg(String msg) {
        StackTraceElement stack = getCallerStack();
        return MessageFormat.format(logFormat, getTag(stack), stack.getMethodName(), stack.getLineNumber(), msg);
    }
}
